package com.example.demo.Impl;

import com.example.demo.dto.MajorManagementResultDTO;
import com.example.demo.entity.Organization;
import com.example.demo.entity.Student;
import com.example.demo.entity.MbtiResult;
import com.example.demo.repository.OrganizationRepository;
import com.example.demo.repository.StudentRepository;
import com.example.demo.repository.MbtiResultRepository;
import com.example.demo.service.MajorManagementService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;

@Service
public class MajorManagementServiceImpl implements MajorManagementService {

    @Autowired
    private OrganizationRepository organizationRepository;

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private MbtiResultRepository mbtiResultRepository;

    @Override
    public List<MajorManagementResultDTO> getMajorResults() {
        List<Organization> majors = organizationRepository.findByType(Organization.OrgType.major);
        List<MajorManagementResultDTO> resultList = new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");

        for (Organization major : majors) {
            MajorManagementResultDTO dto = new MajorManagementResultDTO();
            dto.setId(major.getId());
            dto.setName(major.getName());

            if (major.getParent() != null) {
                dto.setCollegeName(major.getParent().getName());
            } else {
                dto.setCollegeName("未知学院");
            }

            // 获取该专业下所有班级
            List<Organization> clazzes = organizationRepository.findByParent(major);

            List<MajorManagementResultDTO.StudentResult> studentResults = new ArrayList<>();

            for (Organization clazz : clazzes) {
                List<Student> students = studentRepository.findByClazz(clazz);
                for (Student student : students) {
                    List<MbtiResult> results = mbtiResultRepository.findByStudentIdOrderByTestTimeDesc(student.getId());
                    for (MbtiResult r : results) {
                        MajorManagementResultDTO.StudentResult sr = new MajorManagementResultDTO.StudentResult();
                        sr.setStudentName(student.getName());
                        sr.setStudentNo(student.getStudentNo());
                        sr.setMbtiType(r.getMbtiType());
                        sr.setTestTime(r.getTestTime().format(formatter));
                        studentResults.add(sr);
                    }
                }
            }

            dto.setResults(studentResults);
            resultList.add(dto);
        }

        return resultList;
    }
}
